import React, { useState, useRef } from 'react'
import {
  Drawer,
  Space,
  Radio,
  Layout,
  Menu,
  Breadcrumb,
  Row,
  Col,
  Typography,
  Dropdown,
  Tag, Popconfirm,
  message,
  Button,
  Avatar,
  Image,
  Form,
  Input,
  Tooltip

} from 'antd';
import { inject, observer } from 'mobx-react';
import { roleList } from '../../utils/commom';
import { DownOutlined, UserOutlined, MenuUnfoldOutlined, MenuFoldOutlined } from '@ant-design/icons';
import myinfo from '../../mobx/info';
import { Link, withRouter } from 'react-router-dom';
import { DrawerProps } from 'antd/es/drawer';
import { RadioChangeEvent } from 'antd/es/radio';
import { reg } from '../../utils/validate';
import { ajax } from '../../api';
import { baseURL } from '../../api/request';

const { Title } = Typography
const { Header } = Layout;
// console.log(roleList)





function Head(props: any) {
  const {
    userInfo,
    collapsed,
    changeCollapsed,
    flag
  } = props.info

  const files: any = useRef()
  const [form] = Form.useForm()
  const rform = useRef<any>()
  const [visible, setVisible] = useState(false)

  const onClose = () => {
    setVisible(false);
  };
  const showDrawer = () => {

    setVisible(true);
  };

  const onFinish = async (v: any) => {
    // setVisible(false)
    let res = await ajax.changepass(v)
    if (res.code == 200) {
      setVisible(false);
      sessionStorage.removeItem('token')
      myinfo.changeMyInfo({ avatar: '' })
      props.history.push('/login')
    }
  }
  const onFinishFailed = () => {
    message.destroy()
    message.error('请输入正确的信息')
  }
  const menu = (
    <Menu>
      <Menu.Item>
        <Link to='/main'>首页</Link>
      </Menu.Item>
      <Menu.Item>
        个人中心
      </Menu.Item>
      <Menu.Item onClick={showDrawer}>
        修改密码
        {/* <Button type="primary" onClick={showDrawer}> */}
      </Menu.Item>
    </Menu>
  )

  // console.log(userInfo.username);

  const text = '你确定要退出吗?';


  function confirm() {
    message.info('退出成功')
    sessionStorage.removeItem('token')
    myinfo.changeMyInfo({ avatar: '' })
    console.log(props.history);
    props.history.push('/login')
  }
  const clickToUpdate = () => {
    files.current.click()
  }
  const startUpdate = async () => {
    const file: any = files.current.files[0]
    console.log(file)

    const data = new FormData()
    data.append('avatar', file)

    let res: any = await ajax.uploadfile(data)
    if (res.code == 200) {
      ajax.changeinfo({
        avatar: res.path
      })
        .then((result: any) => {
          myinfo.changeMyInfo({ avatar: res.path })
          //方法二
          // myinfo.changeMyInfo({
          //   ...JSON.parse(JSON.stringify(userInfo)),  // 解决Proxy 数据丢失的问题 
          //   avatar:res.path,
          // })
        })
    }
  }

  return (
    <Header style={{ background: '#fff' }} className={flag?"changeClass":""}>
      <div className="logo" />
      <Row style={{ width: '100%', display: 'flex', alignItems: "center", height: '100%' }}>

        <Col span={7} className="flex">
          <Title style={{ color: "black", margin: 0 }} level={4}>
            <i onClick={() => changeCollapsed()} style={{ marginRight: 5, cursor: "pointer", fontSize: 14 }}>  {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined)}</i>

                     中海物业管理中心后台</Title>
         </Col>
        <Col span={9}>
          <div style={{ fontSize: 14, margin: "0 20", fontWeight: 'bold', color: "black", padding: "0 20px", maxWidth: 400 }}>
            物业管理真情在，用心服务传递爱!
          </div>
        </Col>
        <Col style={{ padding: "0 10px" }} span={8}>
          {
            userInfo && <div className='head-user'>
              <span style={{ margin: 10 }}>{userInfo?.username}</span>
              {/* <Avatar src={<Image src="https://joeschmoe.io/api/v1/random" style={{ width: 32 }} />} /> */}
              <Tooltip placement="top" title={'切换头像'}>
                <input type="file" ref={files} onChange={startUpdate} style={{ display: "none" }} name="" id="" />
                {
                  userInfo.avatar ? <img src={userInfo.avatar.replace(/public/, baseURL)} onClick={clickToUpdate} style={{ margin: "0 10px", cursor: 'pointer', width: 36, height: 36, background: "#999", display: 'inline-block', borderRadius: '50%', textAlign: 'center', lineHeight: '36px' }} />
                    : <i onClick={clickToUpdate} style={{ margin: "0 10px", cursor: 'pointer', width: 36, height: 36, background: "#999", display: 'inline-block', borderRadius: '50%', textAlign: 'center', lineHeight: '36px' }}><UserOutlined style={{ fontSize: "18px", color: "#fff" }} /> </i>
                }
              </Tooltip>
              <Tooltip placement="top" title={'身份'} >
                {
                  roleList.map((item, index) => {
                    if (item.value == userInfo.role)
                      return (
                        <Tag color={item.color} key={index} style={{ margin: 10 }}>{item.text}</Tag>
                      )
                  })
                }
              </Tooltip>

              <Popconfirm placement="bottom" title={text} onConfirm={confirm} okText="Yes" cancelText="No">
                <Button style={{ margin: 10 }}>退出登录</Button>
              </Popconfirm>
              <Popconfirm
                placement="bottomRight"
                title={text}
                onConfirm={confirm}
                okText="Yes"
                cancelText="No"
              >
              </Popconfirm>

              <Dropdown overlay={menu} placement="bottomCenter" arrow>
                <Button>更多</Button>
              </Dropdown>

              <Drawer
                title="修改密码"
                placement={'top'}
                width={500}
                onClose={onClose}
                visible={visible}
              >
                <Form layout="vertical" onFinish={onFinish} onFinishFailed={onFinishFailed} form={form} ref={rform} hideRequiredMark>
                  <Row gutter={16}>
                    <Col span={12}>
                      <Form.Item
                        name="oldpass"
                        label="旧密码"
                        rules={[{ required: true, message: '请输入当前密码' },
                        { pattern: reg.pwd, message: '请输入6-16位的数字加字母组合' }]}
                      >
                        <Input.Password placeholder="请输入当前密码" />
                      </Form.Item>
                    </Col>

                  </Row>
                  <Row gutter={16}>
                    <Col span={12}>
                      <Form.Item
                        name="newpass"
                        label="新密码"
                        rules={[{ required: true, message: '请输入新密码' },
                        { pattern: reg.pwd, message: '请输入6-16位的数字加字母组合' }]}
                      >
                        <Input.Password placeholder="请输入新密码" />
                      </Form.Item>

                    </Col>
                  </Row>
                  <Form.Item>
                    <Button onClick={onClose}>取消修改</Button>
                    <Button type="primary" htmlType='submit' >
                      确定修改
                    </Button>
                  </Form.Item>
                </Form>
              </Drawer>
            </div>
          }

        </Col>

      </Row>

    </Header>
  )
}

export default inject('info')(withRouter(observer(Head)))